package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * 图片文件的上传和下载
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    /**
     * 文件上传方法
     * @param file
     * @return
     */
    @Value("${reggie.path}")
    private String loadPath;
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        //file是一个临时文件，需要转存到指定位置
        String oldName=file.getOriginalFilename();//原文件名
        String type=oldName.substring(oldName.lastIndexOf("."));
        String fileName= UUID.randomUUID().toString() +type;
        //目录不存在，则创建该目录
        File dir=new File(loadPath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        try {
            file.transferTo(new File(loadPath+fileName));
        } catch (IOException e) {
            throw new RuntimeException("文件存储失败");
        }
        return R.success(fileName);
    }

    /**
     * 文件下载
     * @param name
     * @param respone
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse respone){
        try {
            //通过输入流读取本地文件内容
            FileInputStream fis=new FileInputStream(new File(loadPath+name));
            //通过输出流把文件写回到浏览器，浏览器来展示图片
            ServletOutputStream outputStream = respone.getOutputStream();
            //返回的类型为图片
            respone.setContentType("image/jpeg");
            //输入流读取到字节数组，字节数组写入到输出流
            byte[] bytes=new byte[1024];
            while(fis.read(bytes)!=-1){
                outputStream.write(bytes);
                outputStream.flush();
            }
            outputStream.close();;
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
